package com.atguigu.dga.assessor.calc;

import com.atguigu.dga.assessor.Assessor;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import com.atguigu.dga.util.SqlUtil;
import lombok.Getter;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Stack;

@Component("SELECT_ALL")
public class SelectAllAssessor extends Assessor {
    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception {
        //筛选去除ODS层的表
        if (assessParam.getTableMetaInfo().getTableMetaInfoExtra().getDwLevel().equals("ODS")){
            return;
        }

        //获取sql
        String tsakSQL = assessParam.getTDsTaskDefinition().getTsakSQL();

        if(tsakSQL== null || tsakSQL.trim().isEmpty()){
            return;
        }

        //解析sql
        SelectAllDispatcher selectAllDispatcher = new SelectAllDispatcher();
        SqlUtil.parseSQL(tsakSQL,selectAllDispatcher);

        //判断并处理结果
        if (selectAllDispatcher.getIsContainsSelectAll()){
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("sql中包含select *");
        }

    }

    public  static class SelectAllDispatcher implements Dispatcher{
        //判断是否有的标记
        @Getter
        private Boolean isContainsSelectAll=false;
        @Override
        public Object dispatch(Node node, Stack<Node> stack, Object... objects) throws SemanticException {
            //获取节点
            ASTNode astNode= (ASTNode) node;

            //每个节点查找,如果有就修改标记
            if (astNode.getType()== HiveParser.TOK_ALLCOLREF){
                isContainsSelectAll=true;
            }
            return null;
        }
    }
}
